<script setup lang="ts">
import type { ChatMessage } from '~/stores/chat'
import { Position } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { computed, nextTick, ref, watch } from 'vue'
import { useChatStore } from '~/stores/chat'

const chatStore = useChatStore()
const messages = computed(() => chatStore.messages)
const inputMessage = ref('')
const messagesContainer = ref<HTMLElement | null>(null)
const isSending = ref(false)

// 滚动到底部
async function scrollToBottom() {
  await nextTick()
  if (messagesContainer.value) {
    const { scrollHeight, clientHeight } = messagesContainer.value
    messagesContainer.value.scrollTo({
      top: scrollHeight - clientHeight,
      behavior: 'smooth',
    })
  }
}

// 监听消息变化，自动滚动到底部
watch(() => messages.value.length, () => {
  scrollToBottom()
})

function formatTime(timestamp: number) {
  const now = dayjs()
  const messageTime = dayjs(timestamp)

  if (messageTime.isSame(now, 'day')) {
    return messageTime.format('HH:mm')
  }
  else if (messageTime.isSame(now.subtract(1, 'day'), 'day')) {
    return `昨天 ${messageTime.format('HH:mm')}`
  }
  else if (messageTime.isSame(now, 'year')) {
    return messageTime.format('M月D日 HH:mm')
  }
  else {
    return messageTime.format('YYYY年M月D日 HH:mm')
  }
}

function shouldShowTime(currentIndex: number) {
  if (currentIndex === 0)
    return true
  const currentMessage = messages.value[currentIndex]
  const prevMessage = messages.value[currentIndex - 1]
  // 如果与上一条消息时间相差超过3分钟，显示时间
  return currentMessage.timestamp - prevMessage.timestamp > 3 * 60 * 1000
}

async function handleKeydown(e: KeyboardEvent) {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    if (!isSending.value && inputMessage.value.trim()) {
      await sendMessage()
    }
  }
}

async function sendMessage() {
  if (isSending.value || !inputMessage.value.trim())
    return

  isSending.value = true

  try {
    // 添加用户消息
    chatStore.addMessage({
      type: 'user',
      content: inputMessage.value,
      timestamp: Date.now(),
    })

    const userMessage = inputMessage.value
    // 清空输入框
    inputMessage.value = ''

    // 等待滚动完成
    await scrollToBottom()

    // 模拟机器人回复
    setTimeout(() => {
      chatStore.addMessage({
        type: 'bot',
        content:
          '在Python中实现多线程主要有两种方式：1. 使用 threading 模块的 Thread 类 2. 继承 Thread 类并重写 run 方法。这里是一个简单的示例：```python import threading import time def worker(): print(f"线程 {threading.current_thread().name} 开始工作") time.sleep(2) print(f"线程 {threading.current_thread().name} 完成工作") # 创建线程 thread = threading.Thread(target=worker) # 启动线程 thread.start() # 等待线程结束 thread.join()```',
        timestamp: Date.now(),
      })
      isSending.value = false
    }, 1000)
  }
  catch (error) {
    console.error('发送消息失败:', error)
    isSending.value = false
  }
}
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      问答对话
    </div>
    <div ref="messagesContainer" class="chat-messages custom-scrollbar">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message-wrapper"
      >
        <div v-if="shouldShowTime(index)" class="time-divider">
          <span>{{ formatTime(message.timestamp) }}</span>
        </div>
        <div
          class="message"
          :class="[message.type === 'user' ? 'user-message' : 'bot-message']"
        >
          <div class="avatar">
            <el-avatar :size="40">
              <svg class="icon" aria-hidden="true">
                <use :xlink:href="message.type === 'user' ? '#icon-yonghufill' : '#icon-a-zhinengjiqirenjiqiren'" />
              </svg>
            </el-avatar>
          </div>
          <div class="content">
            <div class="bubble">
              {{ message.content }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <div class="input-wrapper">
        <el-input
          v-model="inputMessage"
          placeholder="请输入你的问题..."
          :rows="3"
          type="textarea"
          class="custom-scrollbar"
          resize="none"
          @keydown="handleKeydown"
        />
      </div>
      <el-button
        type="primary"
        class="send-button"
        :disabled="!inputMessage.trim() || isSending"
        :loading="isSending"
        @click="sendMessage"
      >
        <template #icon>
          <el-icon><Position /></el-icon>
        </template>
        {{ isSending ? '发送中...' : '发送' }}
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.chat-container {
  max-width: 1400px;
  margin: 10px auto;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 16px 20px;
  font-size: 18px;
  font-weight: 500;
  border-bottom: 1px solid #eee;
  text-align: left;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f5f7fa;
  scroll-behavior: smooth;

  .message-wrapper {
    margin-bottom: 20px;

    .time-divider {
      text-align: center;
      margin: 10px 0;
      color: #999;
      font-size: 12px;

      span {
        background: rgba(0, 0, 0, 0.03);
        padding: 2px 8px;
        border-radius: 4px;
      }
    }
  }

  .message {
    display: flex;
    align-items: flex-start;
    margin: 8px 0;

    .avatar {
      margin-right: 12px;
      flex-shrink: 0;

      .icon {
        width: 24px;
        height: 24px;
        fill: currentColor;
      }
    }

    .content {
      max-width: 70%;

      .bubble {
        padding: 12px 16px;
        border-radius: 8px;
        font-size: 14px;
        line-height: 1.5;
        white-space: pre-wrap;
        word-wrap: break-word;
        word-break: break-all;
      }
    }

    &.user-message {
      flex-direction: row-reverse;

      .avatar {
        margin-right: 0;
        margin-left: 12px;
      }

      .bubble {
        background: #409eff;
        color: white;
      }
    }

    &.bot-message {
      .bubble {
        background: white;
        color: #333;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      }
    }
  }
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
  align-items: flex-start;
  background: white;

  .input-wrapper {
    flex: 1;
    position: relative;

    :deep(.el-textarea) {
      .el-textarea__inner {
        resize: none !important;
        padding: 12px 16px;
        box-sizing: border-box;
        border-radius: 8px;
        transition: all 0.3s ease;
        border-color: #dcdfe6;

        &:hover {
          border-color: #c0c4cc;
        }

        &:focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
        }
      }
    }
  }

  .send-button {
    min-width: 100px;
    height: 73px;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 0 24px;
    font-size: 15px;
    border-radius: 8px;
    background: #409eff;
    border: none;
    margin: 0;

    :deep(.el-icon) {
      font-size: 16px;
      margin-right: 4px;
      transition: transform 0.3s ease;
    }

    &:not(:disabled) {
      &:hover {
        background: #66b1ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

        :deep(.el-icon) {
          transform: translateX(2px);
        }
      }

      &:active {
        transform: translateY(0);
        box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
      }
    }

    &:disabled {
      cursor: not-allowed;
      opacity: 0.6;
      background: #a0cfff;
    }

    &.is-loading {
      background: #a0cfff;
      cursor: default;

      &:hover {
        transform: none;
        box-shadow: none;
      }
    }
  }
}
</style>
